package com.carhailing.alipay.utils;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 发送延迟队列
 *
 * @author Administrator
 */
@Component
public class DelayedQueue {

  /**
   * routingKey
   */
  private static final String DELAYED_ROUTING_KEY = "delayed.routingkey";

  /**
   * 延迟队列交换机
   */
  private static final String DELAYED_EXCHANGE = "delayed.exchange";

  @Autowired
  RabbitTemplate rabbitTemplate;

  @Resource
  RabbitAdmin rabbitAdmin;

  /**
   * 发送延迟队列
   *
   * @param queueName   队列名称
   * @param params      消息内容
   * @param delayedTime 延迟时间 毫秒
   */
  public void sendDelayedQueue(String queueName, Object params, Integer delayedTime) {
    // 先创建一个队列
    Queue queue = new Queue(queueName);
    rabbitAdmin.declareQueue(queue);
    // 创建延迟队列交换机
    CustomExchange customExchange = createCustomExchange();
    rabbitAdmin.declareExchange(customExchange);
    // 将队列和交换机绑定
    Binding binding = BindingBuilder.bind(queue).to(customExchange).with(DELAYED_ROUTING_KEY).noargs();
    rabbitAdmin.declareBinding(binding);
    // 发送延迟消息  方法的参数是一个接口 那么传入 他的实现类 MessagePostProcessor
    rabbitTemplate.convertAndSend(DELAYED_EXCHANGE, DELAYED_ROUTING_KEY, params, message -> {
      // 设置消息的延迟时间
      message.getMessageProperties().setDelay(delayedTime);
      message.getMessageProperties().setMessageId(UUID.randomUUID().toString());
      return message;
    });
  }

  // 指定交换机
  public CustomExchange createCustomExchange() {
    Map<String, Object> arguments = new HashMap<>();
    /**
     * 参数说明：交换机名称，类型，是否持久化，否自动删除，其它参数
     */
    arguments.put("x-delayed-type", "direct");
    return new CustomExchange(DELAYED_EXCHANGE, "x-delayed-message", true, false, arguments);
  }

}

